﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Reflection;
using UnityEditor;
using UnityEditor.SceneManagement;
using UnityEngine;
using System.IO;
namespace TinySkill
{
    public class SkillMergeWindow : EditorWindow
    {
        [MenuItem("Window/SkillMergeEditor")]
        static void Merge()
        {
            EditorWindow.GetWindow(typeof(SkillMergeWindow));
        }

        Vector2 scrollPos;
        string filePath = "";
        List<config_skill> Skill;
        bool[] selected;

        void OnGUI()
        {
            GUIStyle sty = new GUIStyle(GUI.skin.box);

            GUI.Box(new Rect(0, 0, 500, 500), "", sty);
            GUILayout.BeginArea(new Rect(0, 0, 500, 500));

            GUILayout.BeginVertical();

            GUILayout.BeginHorizontal();
            if (GUILayout.Button("选择技能文件", GUILayout.MinWidth(100), GUILayout.Width(100)))
            {
                filePath = EditorUtility.OpenFilePanel("选择技能文件", Path.Combine(Application.streamingAssetsPath, "Skill"), "bin");
                if (!string.IsNullOrEmpty(filePath))
                {
                    if (File.Exists(filePath))
                    {
                        //技能类型比较复杂，自行序列化，不走Unity的序列化
                        MemoryStream ms = new MemoryStream(File.ReadAllBytes(filePath));
                        ms.Position = 0;
                        Skill = ProtoBuf.Serializer.Deserialize<List<config_skill>>(ms);
                        selected = new bool[Skill.Count];
                    }
                }
            }
            GUILayout.Label(filePath);

            GUILayout.EndHorizontal();

            scrollPos = GUILayout.BeginScrollView(scrollPos);

            if (Skill != null)
            {
                for (int i = 0; i < Skill.Count; i++)
                {
                    selected[i] = GUILayout.Toggle(selected[i], string.Format("{0} {1}", Skill[i].id, Skill[i].name));
                }
            }

            GUILayout.EndScrollView();


            if (GUILayout.Button("合并", GUILayout.MinWidth(100), GUILayout.Width(100)))
            {
                SkillEditorEngine.Save();
                Debug.Log("开始合并...");
                Data.LoadSkill();
                for (int i = 0; i < Skill.Count; i++)
                {
                    if (selected[i])
                    {
                        Data.Skill[Skill[i].id] = Skill[i];
                    }
                }
                Debug.Log("合并完成");
                SkillEditorEngine.Save();
            }

            GUILayout.EndVertical();
            GUILayout.EndArea();
        }

    }
}